package com.wj.controller;

import com.wj.entity.User;
import com.wj.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CacheConfig(cacheNames = "myCache")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
    //放到缓存中
    @CachePut(key ="#result.id+'abc'")//key:userCache::user.id;
//    @CachePut(cacheNames = "userCache",key = "#result.id")//key:userCache::user.id;
//    @CachePut(cacheNames = "userCache",key = "#p0.id")//key:userCache::user.id;
//    @CachePut(cacheNames = "userCache",key = "#a0.id")//key:userCache::user.id;
//    @CachePut(cacheNames = "userCache",key = "#root.args[0].id")//key:userCache::user.id;
    public User save(@RequestBody User user) {
        userMapper.insert(user);
        return user;
    }

    @DeleteMapping
    @CacheEvict(key = "#id")//清理单个缓存数据
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @DeleteMapping("/delAll")//都需要序列化对象数据，F6调试向下执行，allEntries = true，清理userCache的所有缓存
    @CacheEvict(allEntries = true)//清理所有缓存数据
    public void deleteAll() {
        userMapper.deleteAll();
    }

    @GetMapping
//    @Cacheable(cacheNames = "userCache", key = "#id")//如果有返回数据，如果没有，调用方法的返回值会放到缓存中
    @Cacheable(key = "#id+'abc'")
    public User getById(Long id) {
        User user = userMapper.getById(id);
        return user;
    }

    @PutMapping
    @CacheEvict(key = "#user.id")
    public boolean updateById(@RequestBody User user) {
        //只有当方法成功执行（返回 true）时，缓存清除操作才会被触发。
        int i = userMapper.updateUser(user);
        return i>0;
    }


    //修改需要根据id清除以前的缓存数据，利用id,在查询的时候又加上缓存数据
    //删除就是删除一个或者多个缓存数据和sql数据 @CacheEvict(cacheNames = "userCache", key = "#id")
    //查询一般根据id或者唯一标识查询第一次数据方法返回值存入到缓存数据当中去，后面就不用了； @Cacheable(cacheNames = "userCache", key = "#id")
    // @CachePut(cacheNames = "userCache", key = "#result.id")：增加一条数据使用id增加相关的redis的key
}
